<template>
  <el-cascader
    placeholder="请选择地区"
    filterable
    :clearable="true"
    :options="regionTree"
    :props="props"
    @change="handleItemChange"
    v-model="areaIds">
  </el-cascader>
</template>

<script>
  import ComponentApi from "@/api/components/component";
  export default{
    props:{
      areaValues: {
        type: Array,
        default:() => []
      },
      isChangeOnSelect: {
        type: Boolean,
        default: () => false
      }
    },
    data(){
        return {
          regionTree: [],
          props:{
            checkStrictly:this.isChangeOnSelect
          },
          areaIds: []
        }
    },
    methods:{
      getRegionTree(){
        ComponentApi.treeRegion()
        .then(res => {
          this.regionTree = res.data[0].children;
          this.removeChildren(this.regionTree);
        });
      },
      removeChildren(regions){
        for(let i= 0,len = regions.length;i<len;i++){
          if(regions[i].children.length === 0){
            delete regions[i].children;
          }else {
            this.removeChildren(regions[i].children)
          }
        }
      },
      handleItemChange(val){
        var cityValue = "";
        var areaValue = "";
        let province = this.regionTree.filter(item => {
          return item.value == val[0]
        })
        if(val[1]){
          let city = province[0].children.filter(item => {
              return item.value == val[1];
          })
          cityValue = city[0].label
          if(val[2]){
            let area = city[0].children.filter(item => {
                return item.value == val[2];
            })
            areaValue = area[0].label
          }
        }
        this.$emit("regionChange",{
          provinceId :val[0],
          provinceName: province[0].label,
          cityId: val[1]? val[1] : "",
          cityName: cityValue,
          areaId:  val[2]? val[2] : "",
          areaName: areaValue
        });
      }
    },
    mounted(){
      this.getRegionTree();
    },
    watch:{
      areaValues(curVal){
        let ids = [];
        curVal.forEach((item, index)=>{
          if (item){
            ids[index] = parseInt(item);
          }
        });
        this.areaIds = ids;
      }
    },
  }
</script>
